import React, { useEffect } from "react"


enum Role {
  admin = 'admin',
  user = 'user',
}

const withAuthorization = (role: Role) => {
  return (Component: React.FC) => {
    const isAuth = (role: Role) => role === Role.admin
    return (props: any) => {
      if (isAuth(role)) {
        return <Component {...props} />
      } else {
        return <div>无权限</div>
      }
    }
  }
}

const AdminComponent = withAuthorization(Role.admin)((props: any) => <div>admin{props.a}</div>)
const UserComponent = withAuthorization(Role.user)((props: any) => <div>user{props.a}</div>)

// 例子2 
const trackService = {
  sendEvent: <T,>(trackType: string, data: T = null as T) => {
    const eventData = {
      timestamp: new Date().toISOString(), //时间戳
      trackType, //事件类型
      data, //事件数据
      url: window.location.href, //当前页面url
      ua: navigator.userAgent, //浏览器信息
    }
    // 发送埋点数据
    navigator.sendBeacon('/api/track', JSON.stringify(eventData))
  }
}
// trackService.sendEvent('button-click', {
//   name: 'button',
//   clientX: 100,
//   clientY: 100
// })

const withTrack = <T,>(Component: React.ComponentType<T>, trackType: string) => {
  return (props: T) => {
    // const trackEvent = (eventType: string, data: T) => {
    //   trackService.sendEvent(eventType, data)
    // }
    useEffect(() => {
      trackService.sendEvent(`${trackType}-mount`)

      return () => {
        trackService.sendEvent(`${trackType}-unmount`)
      }
    }, [])

    const trackEvent = (eventType: string, data: T) => {
      trackService.sendEvent(`${trackType}-${eventType}`, data)
    }

    return <Component {...props} trackEvent={trackEvent} />
  }
}

const Button = ({ trackEvent }: { trackEvent: (eventType: string, data: any) => void }) => {
  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    trackEvent(e.type, {
      name: 'button',
      clientX: e.clientX,
      clientY: e.clientY
    })
  }
  return (
    <button onClick={handleClick}>click me</button>
  )
}

const ButtonWithTrack = withTrack(Button, 'button')


export default function HOC() {
  return (
    <div>
      <h1>HOC高阶组件</h1>
      <AdminComponent a={1} />
      <UserComponent a={1} />
      <div>ButtonWithTrack</div>
      <ButtonWithTrack />
    </div>
  )
}